package devkit.commando {
	
	import mx.rpc.events.FaultEvent;
	
	/**
	 * Base command class that should be extended by all generic command classes.
	 * @author Francois Dempers
	 */
	public class CommandBase {
		
		/** Propagation mode to only call the local error handler. */
		public static const HANDLE_LOCAL:int = 0;
		
		/** Propagation mode to only call the global error handler. */
		public static const HANDLE_GLOBAL:int = 1;
		
		/** Propagation mode to call both the local and global error handlers. */
		public static const HANDLE_BOTH:int = 2;
		
		/** The function to invoke when the command returns a result. */
		public var resultHandler:Function;
		
		/** The function to invoke when the command returns a fault. */
		public var faultHandler:Function;
		
		/**
		 * Creates a new <code>CommandBase</code>.
		 * @param handler The client side function to invoke when a result is received.
		 */
		public function CommandBase(result:Function, fault:Function) {
			
			resultHandler = result;
			faultHandler = fault;
		}
		
		/**
		 * Send the result of the command to it's result handler.
		 * @param result The result to dispacth.resultHandler
		 */
		protected function dispatchResult(result:*):void {
			
			if(resultHandler != null) {
				resultHandler.call(this, result);
			}
			CommandManager.processChain.removeCommand(this);
		}
		
		/**
		 * Sends a fault returned by a command to its selected fault handlers.
		 * @param mode The propagation mode of the error, can be either ERROR_LOCAL, ERROR_GLOBAL, ERROR_ALL
		 * @param result The result to dispacth.resultHandler
		 */
		protected function dispatchFault(mode:int, fault:FaultEvent):void {
			
			if(faultHandler != null) {
				if(mode == HANDLE_LOCAL || mode == HANDLE_BOTH) {
					faultHandler.call(this, fault);
				}
			}
			
			if(mode == HANDLE_GLOBAL || mode == HANDLE_BOTH) {
				CommandManager.errorChain.logError(this, fault);
			}
			
			CommandManager.processChain.removeCommand(this);
		}
	}
}